<template>
  <div class="prescription-order-management">
    <!-- 页面标题 -->
    <div class="page-title">
      <h2>处方流转订单管理</h2>
    </div>
    
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-header">
        <i class="filter-icon">📊</i>
        <span>筛选</span>
      </div>
      <div class="filter-content">
        <div class="filter-item">
          <label>患者姓名或手机号：</label>
          <input 
            type="text" 
            v-model="filter.patientNameOrPhone" 
            placeholder="输入患者姓名或手机号"
            class="filter-input"
          />
        </div>
        <div class="filter-item">
          <label>日期：</label>
          <input 
            type="datetime-local" 
            v-model="filter.startTime" 
            class="filter-input"
          />
          <span class="date-separator">至</span>
          <input 
            type="datetime-local" 
            v-model="filter.endTime" 
            class="filter-input"
          />
        </div>
        <button @click="applyFilter" class="filter-button">筛选</button>
      </div>
    </div>
    
    <!-- 数据列表区域 -->
    <div class="data-list-section">
      <div class="data-list-header">
        <i class="data-icon">📋</i>
        <span>数据列表</span>
      </div>
      
      <!-- 状态切换按钮 -->
      <div class="status-tabs">
        <button 
          v-for="tab in statusTabs" 
          :key="tab.key ?? 'all'"
          @click="switchStatus(tab.key)"
          :class="['status-tab', { active: currentStatus === tab.key }]"
        >
          {{ tab.label }}
        </button>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <!-- 数据表格 -->
      <div v-else class="data-table">
        <div class="table-header">
          <span>订单编号</span>
          <span>处方编号</span>
          <span>患者</span>
          <span>科室</span>
          <span>医生</span>
          <span>费用</span>
          <span>订单状态</span>
          <span>处方单状态</span>
          <span>购药方式</span>
          <span>发药状态</span>
          <span>操作</span>
        </div>
        <div v-if="dataList.length === 0" class="empty-data">
          <p>暂无数据</p>
        </div>
        <div class="table-row" v-for="item in dataList" :key="item.id">
          <span>{{ item.orderNo || '-' }}</span>
          <span>{{ item.prescriptionNo || '-' }}</span>
          <span>{{ item.patientName || '-' }}</span>
          <span>{{ item.departmentName || '-' }}</span>
          <span>{{ item.doctorName || '-' }}</span>
          <span>¥{{ item.paymentAmount || 0 }}</span>
          <span :class="['status', getStatusClass(item.status)]">{{ item.statusText || '未知' }}</span>
          <span>{{ item.prescriptionStatusText || '-' }}</span>
          <span>{{ item.purchaseMethod || '-' }}</span>
          <span>{{ item.dispensingStatus || '-' }}</span>
          <span class="action">
            <button @click="viewDetail(item)" class="action-button view">查看</button>
          </span>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-section">
        
        <div class="pagination">
          <span class="pagination-info">共{{ pagination.totalPages }}页/{{ pagination.totalCount }}条数据</span>
          <div class="pagination-controls">
            <button 
              @click="changePage(pagination.currentPage - 1)" 
              :disabled="pagination.currentPage <= 1"
              class="page-btn"
            >
              &lt;
            </button>
            <button 
              v-for="page in visiblePages" 
              :key="page"
              @click="changePage(page)"
              :class="['page-btn', { active: pagination.currentPage === page }]"
            >
              {{ page }}
            </button>
            <button 
              @click="changePage(pagination.currentPage + 1)" 
              :disabled="pagination.currentPage >= pagination.totalPages"
              class="page-btn"
            >
              &gt;
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onActivated, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import api from '../utils/request';

const router = useRouter();
const route = useRoute();

// 筛选条件
const filter = reactive({
  patientNameOrPhone: '',
  startTime: '',
  endTime: ''
});

// 状态相关
const currentStatus = ref<number | null>(null);
const statusTabs = [
  { key: null as number | null, label: '全部' },
  { key: 0, label: '待支付' },
  { key: 1, label: '已完成' },
  { key: 2, label: '已失效' }
];

// 数据相关
const dataList = ref<any[]>([]);
const loading = ref(false);

// 分页相关
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  totalCount: 0,
  totalPages: 0
});



// 计算属性
const visiblePages = computed(() => {
  const pages = [];
  const start = Math.max(1, pagination.currentPage - 2);
  const end = Math.min(pagination.totalPages, pagination.currentPage + 2);
  
  for (let i = start; i <= end; i++) {
    pages.push(i);
  }
  
  return pages;
});

// 方法
const loadData = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params: any = {};

    // 分页参数
    params.pageIndex = pagination.currentPage;
    params.pageSize = pagination.pageSize;

    // 患者信息筛选
    if (filter.patientNameOrPhone && filter.patientNameOrPhone.trim()) {
      params.patientNameOrPhone = filter.patientNameOrPhone.trim();
    }

    // 状态筛选
    if (currentStatus.value !== null) {
      params.status = currentStatus.value;
    }

    // 时间筛选
    if (filter.startTime) {
      params.startTime = new Date(filter.startTime).toISOString();
    }

    if (filter.endTime) {
      params.endTime = new Date(filter.endTime).toISOString();
    }

    console.log('发送API请求，参数:', params);

    const response = await api.prescriptionOrder.getPagedList(params);
    
    console.log('API响应:', response);
    
    if (response && response.data) {
      dataList.value = response.data.items || [];
      pagination.totalCount = response.data.totalCount || 0;
      pagination.totalPages = response.data.totalPages || 0;
      pagination.currentPage = response.data.currentPage || 1;
      
      console.log('数据加载成功:', {
        items: dataList.value.length,
        totalCount: pagination.totalCount,
        totalPages: pagination.totalPages,
        currentPage: pagination.currentPage
      });
    } else {
      console.error('获取数据失败，响应格式不正确');
      dataList.value = [];
    }
  } catch (error) {
    console.error('请求失败:', error);
    dataList.value = [];
  } finally {
    loading.value = false;
  }
};

const applyFilter = () => {
  pagination.currentPage = 1;
  loadData();
};

const switchStatus = (status: number | null) => {
  currentStatus.value = status;
  pagination.currentPage = 1;
  loadData();
};

const changePage = (page: number) => {
  if (page >= 1 && page <= pagination.totalPages) {
    pagination.currentPage = page;
    loadData();
  }
};



const viewDetail = (item: any) => {
  console.log('查看详情:', item);
  // 跳转到处方流转订单详情页面
  router.push(`/prescription-order-detail/${item.id}`);
};



const getStatusClass = (status: number | null) => {
  switch (status) {
    case 0: return 'pending-payment';
    case 1: return 'completed';
    case 2: return 'expired';
    default: return 'unknown';
  }
};

// 监听路由参数变化，当有refresh参数时重新加载数据
watch(() => route.query.refresh, (newVal) => {
  if (newVal === 'true') {
    loadData();
    // 清除refresh参数
    router.replace({ query: {} });
  }
});

// 生命周期
onMounted(() => {
  loadData();
});

onActivated(() => {
  loadData();
});
</script>

<style scoped>
.prescription-order-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-title {
  margin-bottom: 20px;
}

.page-title h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  color: #333;
  font-weight: 600;
}

.filter-icon {
  font-size: 16px;
}

.filter-content {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-weight: 500;
  color: #666;
  white-space: nowrap;
}

.filter-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 200px;
}

.filter-input:focus {
  outline: none;
  border-color: #1890ff;
}

.date-separator {
  color: #666;
  margin: 0 8px;
}

.filter-button {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.filter-button:hover {
  background-color: #40a9ff;
}

.data-list-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-list-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  color: #333;
  font-weight: 600;
}

.data-icon {
  font-size: 16px;
}

.status-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.status-tab {
  padding: 8px 16px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

.status-tab:hover {
  color: #1890ff;
}

.status-tab.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
}

.loading-container {
  text-align: center;
  padding: 40px;
  color: #999;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.data-table {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
}

.table-header {
  display: grid;
  grid-template-columns: 50px 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 120px;
  background-color: #fafafa;
  padding: 12px 16px;
  font-weight: 600;
  color: #333;
  font-size: 14px;
  border-bottom: 1px solid #f0f0f0;
}

.table-row {
  display: grid;
  grid-template-columns: 50px 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 120px;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  align-items: center;
  font-size: 14px;
  color: #333;
}

.table-row:hover {
  background-color: #f9f9f9;
}

.checkbox-cell {
  display: flex;
  justify-content: center;
  align-items: center;
}



.status {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
}

.status.pending-payment {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status.completed {
  background-color: #f6ffed;
  color: #52c41a;
}

.status.expired {
  background-color: #fff1f0;
  color: #f5222d;
}

.status.unknown {
  background-color: #f5f5f5;
  color: #999;
}

.action {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-button {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.action-button.view {
  background-color: #1890ff;
  color: white;
}

.action-button.view:hover {
  background-color: #40a9ff;
}



.empty-data {
  text-align: center;
  padding: 40px;
  color: #999;
}

.pagination-section {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 16px;
}

.pagination-info {
  font-size: 14px;
  color: #666;
}

.pagination-controls {
  display: flex;
  gap: 4px;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  background: white;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.3s;
}

.page-btn:hover:not(:disabled) {
  border-color: #1890ff;
  color: #1890ff;
}

.page-btn.active {
  background-color: #1890ff;
  border-color: #1890ff;
  color: white;
}

.page-btn:disabled {
  background-color: #f5f5f5;
  color: #d9d9d9;
  cursor: not-allowed;
  border-color: #f0f0f0;
}
</style>